<template>
  <div class="container">
    <Breadcrumb
      :items="['menu.tenant-management', 'menu.tenant-management.searchTable']"
    />
    <a-card
      v-if="mainVisible == true"
      class="general-card"
      :title="$t('menu.tenant-management.searchTable')"
    >
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="number" label="租户名称">
                  <a-input
                    v-model="formModel.username"
                    placeholder="请输入租户名称……"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 42px" direction="vertical" />
        <a-col :flex="'192px'" style="text-align: right">
          <a-space direction="horizontal" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button type="primary" @click="handleCreate">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <!-- 这里是批量导出的假按钮 -->
          <a-button @click="downloadButton">
            <template #icon>
              <icon-download />
            </template>
            {{ $t('searchTable.operation.download') }}
          </a-button>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
      >
        <template #columns>
          <a-table-column title="租户名称" data-index="username" />
          <a-table-column title="租户密码" data-index="password" />
          <a-table-column title="租户昵称" data-index="nickname">
          </a-table-column>
          <a-table-column title="手机号" data-index="mobile"> </a-table-column>
          <a-table-column title="邮箱" data-index="email" />
          <a-table-column title="创建时间" data-index="createDate" />
          <a-table-column
            :title="$t('searchTable.columns.operations')"
            data-index="operations"
          >
            <template #cell="record">
              <a-button
                type="text"
                status="warning"
                size="small"
                @click="handleModify(record)"
              >
                <!-- {{ $t('searchTable.columns.operations.view') }} -->
                修改
              </a-button>
              <a-button
                type="text"
                status="danger"
                size="small"
                @click="deleteZuhu(record)"
              >
                <!-- {{ $t('searchTable.columns.operations.view') }} -->
                删除
              </a-button>
              <a-button
                type="text"
                status="error"
                size="small"
                @click="history(record)"
              >
                历史
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>

      <create-zuhu v-model:visible="createVisible"></create-zuhu>
      <modify-zuhu
        v-if="modifyVisible"
        v-model:visible="modifyVisible"
        :dialog-table-value="dialogTableValue"
        @fetchData="fetchData"
      ></modify-zuhu>
    </a-card>

    <!-- 查看用户历史的部分 -->
    <a-card v-if="mainVisible == false" title="租户历史">
      <!--  返回的按钮  -->
      <a-button @click="backButton"> 返回 </a-button>
      <!-- 真正展示数据 -->
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination1"
        :data="historyCon"
        :bordered="false"
        @page-change="onPageChange1"
      >
        <template #columns>
          <a-table-column title="密码" data-index="password" />
          <a-table-column title="昵称" data-index="nickname" />
          <a-table-column title="邮箱" data-index="email" />
          <a-table-column title="手机号" data-index="mobile" />
          <a-table-column
            :title="$t('searchTable.columns.operations')"
            data-index="operations"
          >
            <!-- 获取一行的信息 -->
            <template #cell="record">
              <a-button
                type="text"
                status="warning"
                size="small"
                @click="deleteHistory(record)"
              >
                删除
              </a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
      <template #title> 下载确认框 </template>
      <div>点击确定即可下载所有租户具体信息！</div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, createElementBlock } from 'vue';
  import { useI18n } from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import { deleteUser, useIdFindHistory, useIdDeleteHistory } from '@/api/user';
  import { queryPolicyList, PolicyRecord, PolicyParams } from '@/api/list';
  import { Pagination } from '@/types/global';
  import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface';
  import { Message } from '@arco-design/web-vue';

  import createZuhu from './createZuhu.vue';
  import modifyZuhu from './modifyZuhu.vue';

  const generateFormModel = () => {
    return {
      username: '',
      name: '',
      contentType: '',
      filterType: '',
      createdTime: [],
      status: '',
    };
  };
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<PolicyRecord[]>([]);
  const formModel = ref(generateFormModel());

  const dialogTableValue = ref({});

  const basePagination: Pagination = {
    page: 1,
    limit: 20,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const role = '1';
  const createVisible = ref(false);
  const modifyVisible = ref(false);
  const handleModify = (data: any) => {
    modifyVisible.value = true;
    console.log(data.record);
    dialogTableValue.value = JSON.parse(JSON.stringify(data.record));
    console.log(dialogTableValue.value);
  };
  const handleCreate = () => {
    createVisible.value = true;
  };
  const contentTypeOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.contentType.img'),
      value: 'img',
    },
    {
      label: t('searchTable.form.contentType.horizontalVideo'),
      value: 'horizontalVideo',
    },
    {
      label: t('searchTable.form.contentType.verticalVideo'),
      value: 'verticalVideo',
    },
  ]);
  const filterTypeOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.filterType.artificial'),
      value: 'artificial',
    },
    {
      label: t('searchTable.form.filterType.rules'),
      value: 'rules',
    },
  ]);
  const statusOptions = computed<SelectOptionData[]>(() => [
    {
      label: t('searchTable.form.status.online'),
      value: 'online',
    },
    {
      label: t('searchTable.form.status.offline'),
      value: 'offline',
    },
  ]);
  const fetchData = async (
    params: PolicyParams = {
      page: 1,
      limit: 20,
      role,
      username: formModel.value.username,
      isDeleted: '0',
    }
    // params
  ) => {
    setLoading(true);
    try {
      console.log(formModel.value.username);
      const { data } = await queryPolicyList(params);
      renderData.value = data.list;
      pagination.page = params.page;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData({
      ...basePagination,
      ...formModel.value,
    } as unknown as PolicyParams);
  };
  const onPageChange = (page: number) => {
    fetchData({ ...basePagination, page });
  };

  fetchData();
  const reset = () => {
    formModel.value = generateFormModel();
  };

  const visible = ref(false);

  // 点击下载后的方法
  const downloadButton = () => {
    visible.value = true;
  };

  // const handleClick = () => {
  //   visible.value = true;
  // };
  const handleOk = () => {
    visible.value = false;
    Message.success('下载成功!');
  };
  const handleCancel = () => {
    visible.value = false;
  };

  const basePagination1: Pagination = {
    page: 1,
    limit: 20,
  };
  const pagination1 = reactive({
    ...basePagination1,
  });
  const onPageChange1 = (page: number) => {
    fetchData({ ...basePagination1, page });
  };

  // 租户历史部分
  // 主页面是否可见
  const mainVisible = ref(true);
  // 针对历史的变量
  const historyCon = ref({});
  // 下面是用户历史
  const history = async (record: any) => {
    mainVisible.value = false;

    // 然后要发请求了
    const toBack = {
      page: 0,
      answerLimit: 10,
      userId: record.record.id,
    };
    const { data } = await useIdFindHistory(toBack);
    console.log('查询用户历史');
    console.log(data);
    // 这才是需要的 赋值
    console.log(data.list);
    historyCon.value = data.list;
  };
  // 返回的按钮
  const backButton = () => {
    mainVisible.value = true;
  };

  // 删除历史
  const deleteHistory = async (record: any) => {
    console.log(record.record.id);
    await useIdDeleteHistory([record.record.id]);
    Message.success('删除成功');
    // 再发一次查询历史的接口
    const toBack = {
      page: 0,
      answerLimit: 10,
      userId: record.record.userId,
    };
    const { data } = await useIdFindHistory(toBack);
    historyCon.value = data.list;
  };

  // 在查询页面删除
  const deleteZuhu = async (record: any) => {
    await deleteUser([record.record.id]);
    Message.success('删除成功');
    fetchData();
  };
</script>

<script lang="ts">
  export default {
    name: 'SearchTable',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>

function reocrd(reocrd: any) { throw new Error('Function not implemented.'); }
function async(reocrd: any) { throw new Error('Function not implemented.'); }
